import ast

import requests
import logging
import xmltodict
import os
import time
from urllib.parse import unquote
from django.core.cache import cache
from django.http import HttpResponse
import urllib.parse
from django.conf import settings
from django.views.decorators.csrf import csrf_exempt
from client.models import ClientVisit, ClientVisitReplyDaily, ClientVisitReplyDailyReview
from sdk.sdk.WXBizJsonMsgCrypt import WXBizJsonMsgCrypt
from sdk.sdk.WXBizMsgCrypt3 import WXBizMsgCrypt
from user.models import User

logger = logging.getLogger("log")
HOST = "https://qyapi.weixin.qq.com/cgi-bin/"
CORPID = "wwcb3168f059eec7d6"
AGENTID = "1000002"
SECRET = "d4I_Lj-wFI0rv6r81WNHt9RtvMoBmQfEktcNpdgvbkM"
TOKEN = "11v7ru7vWF4Q8UO"
AESKEY = "35EscvXJcf9lzEsiALxcwmtqNulHV4a37IfLUPei9SP"
dailyTemplateId = "C4WoqH6uPrbiMh1DXQdmdiADCCGLmqaRdwdit46Ar"
iceTemplateId = "C4WoqH6uPrbiMh1DXQdmdiADCCGLmqaRdwdit46Ar"


def getNewAccessToken():
    apiName = "获取全新ACCESS_TOKEN"
    logger.info(f"接口>>>{apiName}>>>开始调用")
    code = 0
    msg = "OK"
    data = {}
    url = HOST + "gettoken?corpid=" + CORPID + "&corpsecret=" + SECRET
    try:
        response = requests.get(url)
        responseJson = response.json()
        logger.info(f"接口>>>{apiName}>>>返回结果>>>\n{responseJson}")
        if responseJson["errcode"] != 0:
            code = 1
            msg = responseJson["errmsg"]
            apiOutput = f"1.code<{code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiName}>>>执行失败>>>{apiOutput}")
        else:
            access_token = responseJson["access_token"]
            data["access_token"] = access_token
            apiOutput = f"1.code<{code}>;2.msg<{msg}>;3.access_token<{access_token}>;"
            logger.info(f"接口>>>{apiName}>>>执行成功>>>\n{apiOutput}")
    except Exception as e:
        code = 1
        msg = "未知异常"
        apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    ret = {"code": code, "msg": msg, "data": data}
    return ret


def getAccessToken():
    apiName = "获取ACCESS_TOKEN"
    logger.info(f"接口>>>{apiName}>>>开始调用")
    if cache.has_key("wecom_access_token"):
        access_token = cache.get("wecom_access_token")
        apiOutput = f"1.code<0>; 2.msg<从缓存获取>;"
        logger.info(f"接口>>>{apiName}>>>执行成功>>>\n{apiOutput}")
        return access_token
    else:
        response = getNewAccessToken()
        if response["code"] == 0:
            access_token = response["data"]["access_token"]
            cache.set("wecom_access_token", access_token, 7200)
            apiOutput = f"1.code<0>; 2.msg<重新获取>;"
            logger.info(f"接口>>>{apiName}>>>执行成功>>>\n{apiOutput}")
            return access_token
        else:
            return False


def sendTextMsgApi(touser, content):
    code = 0
    msg = "success"
    data = {}
    apiName = "文本消息"
    logger.info(f"接口>>>{apiName}>>>开始调用")
    ACCESS_TOKEN = getAccessToken()
    if not ACCESS_TOKEN:
        code = 1
        msg = "获取access_token失败"
        apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
        return {"code": code, "msg": msg, "data": data}
    url = HOST + "message/send?access_token=" + ACCESS_TOKEN
    apiInput = f"1.touser<{touser}>;"
    logger.info(f"接口>>>{apiName}>>>入参>>>\n{apiInput}")
    d = {
        "touser": touser,
        "msgtype": "text",
        "agentid": AGENTID,
        "text": {
            "content": content
        }
    }
    try:
        response = requests.post(url, json=d)
        responseJson = response.json()
        logger.info(f"接口>>>{apiName}>>>返回结果>>>\n{responseJson}")
        if responseJson["errcode"] != 0:
            code = responseJson["errcode"]
            msg = responseJson["errmsg"]
            apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
            logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
        else:
            msgid = responseJson["msgid"]
            data["msgid"] = msgid
            apiOutput = f"1.code<{code}>;2.msg<{msg}>;3.msgid<{msgid}>;"
            logger.info(f"接口>>>{apiName}>>>执行成功>>>\n{apiOutput}")
    except Exception as e:
        print("未知异常")
        print(e)
        code = 1
        msg = "未知异常"
        apiOutput = f"1.code<{code}>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    return {"code": code, "msg": msg, "data": data}


def getFormInfoApi(formid):
    code = 0
    msg = "success"
    data = {}
    apiName = "获取收集表信息"
    logger.info(f"接口>>>{apiName}>>>开始调用")
    ACCESS_TOKEN = getAccessToken()
    if not ACCESS_TOKEN:
        code = 1
        msg = "获取access_token失败"
        apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>{apiOutput}")
        return {"code": code, "msg": msg, "data": data}
    url = HOST + "wedoc/get_form_info?access_token=" + ACCESS_TOKEN
    d = {"formid": formid}
    apiInput = f"1.formid<{formid}>;"
    logger.info(f"接口>>>{apiName}>>>入参>>>\n{apiInput}")
    try:
        response = requests.post(url, json=d)
        responseJson = response.json()
        logger.info(f"接口>>>{apiName}>>>返回结果>>>\n{responseJson}")
        if responseJson["errcode"] != 0:
            code = responseJson["errcode"]
            msg = responseJson["errmsg"]
            apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
            logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
        else:
            form_info = responseJson["form_info"]
            apiOutput = f"1.code<{code}>;2.msg<{msg}>;3.form_info<{form_info}>;"
            logger.info(f"接口>>>{apiName}>>>执行成功>>>\n{apiOutput}")
            form_title = form_info["form_title"]
            form_header = form_info["form_header"]
            repeated_id = form_info["repeated_id"][0]
            data["form_title"] = form_title
            data["form_header"] = form_header
            data["repeated_id"] = repeated_id
    except Exception as e:
        print("未知异常")
        print(e)
        code = 1
        msg = "未知异常"
        apiOutput = f"1.code<{code}>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    return {"code": code, "msg": msg, "data": data}


def get_file_name(url, headers):
    filename = ''
    if 'Content-Disposition' in headers and headers['Content-Disposition']:
        disposition_split = headers['Content-Disposition'].split(';')
        if len(disposition_split) > 1:
            if disposition_split[1].strip().lower().startswith('filename='):
                file_name = disposition_split[1].split('=')
                if len(file_name) > 1:
                    filename = unquote(file_name[1])
    if not filename and os.path.basename(url):
        filename = os.path.basename(url).split("?")[0]
    if not filename:
        return time.time()
    return filename


# 微盘下载文件
def wedriveFileDownloadApi(fileid):
    code = 0
    msg = "success"
    data = {}
    apiName = "微盘下载文件"
    logger.info(f"接口>>>{apiName}>>>开始调用")
    ACCESS_TOKEN = getAccessToken()
    if not ACCESS_TOKEN:
        code = 1
        msg = "获取access_token失败"
        apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>{apiOutput}")
        return {"code": code, "msg": msg, "data": data}
    url = HOST + "wedrive/file_download?access_token=" + ACCESS_TOKEN
    d = {"fileid": fileid}
    apiInput = f"1fileid<{fileid}>;"
    logger.info(f"接口>>>{apiName}>>>入参>>>\n{apiInput}")
    try:
        response = requests.post(url, json=d)
    except Exception as e:
        print("未知异常")
        print(e)
        code = 1
        msg = "未知异常"
        apiOutput = f"1.code<{code}>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    responseJson = response.json()
    logger.info(f"接口>>>{apiName}>>>返回结果>>>\n{responseJson}")
    if responseJson["errcode"] != 0:
        code = responseJson["errcode"]
        msg = responseJson["errmsg"]
        apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    else:
        download_url = responseJson["download_url"]
        cookie_name = responseJson["cookie_name"]
        cookie_value = responseJson["cookie_value"]
        apiOutput = f"1.code<{code}>;2.msg<{msg}>;3.download_url<{download_url}>;"
        logger.info(f"接口>>>{apiName}>>>执行成功>>>\n{apiOutput}")
        # 下载下来
        # fileid = "i.wwcb3168f059eec7d6.5629499719587278_f.704534468zJva"
        cookies = {cookie_name: cookie_value}
        downRes = requests.get(download_url, cookies=cookies, stream=True)
        fileName = get_file_name(download_url, downRes.headers)
        fileName = fileName.strip('"')
        fileNameSuffix = fileName.split(".")[-1]
        file_name = fileid + "." + fileNameSuffix
        path = os.path.join(
            settings.MEDIA_ROOT,
            "wedrive",
        )
        file_path = os.path.join(path, file_name)
        try:
            with open(file_path, 'wb+') as f:
                for chunk in downRes.iter_content(chunk_size=1024):
                    if chunk:
                        f.write(chunk)
            data["file_path"] = file_path
        except Exception as e:
            print("未知异常")
            print(e)
            code = 1
            msg = "未知异常"
            apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
            logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    return {"code": code, "msg": msg, "data": data}


# 上传临时素材
def uploadMediaApi(file_path):
    code = 0
    msg = "success"
    data = {}
    apiName = "上传临时素材"
    logger.info(f"接口>>>{apiName}>>>开始调用")
    ACCESS_TOKEN = getAccessToken()
    if not ACCESS_TOKEN:
        code = 1
        msg = "获取access_token失败"
        apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
        return {"code": code, "msg": msg, "data": data}
    url = HOST + "media/upload?access_token=" + ACCESS_TOKEN
    url += "&type=image"
    files = {'file': open(file_path, 'rb')}
    apiInput = f"1.file_path<{file_path}>;"
    logger.info(f"接口>>>{apiName}>>>入参>>>{apiInput}")
    try:
        response = requests.post(url, files=files)
    except Exception as e:
        print("未知异常")
        print(e)
        code = 1
        msg = "未知异常"
        apiOutput = f"1.code<{code}>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    responseJson = response.json()
    logger.info(f"接口>>>{apiName}>>>返回结果>>>\n{responseJson}")
    if responseJson["errcode"] != 0:
        code = responseJson["errcode"]
        msg = responseJson["errmsg"]
        apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    else:
        media_id = responseJson["media_id"]
        apiOutput = f"1.code<{code}>;2.msg<{msg}>;3.media_id<{media_id}>;"
        logger.info(f"接口>>>{apiName}>>>执行成功>>>\n{apiOutput}")
        data["media_id"] = media_id
    return {"code": code, "msg": msg, "data": data}


# 处理收集照片
def processFormPhotos(photoLst):
    photos = []
    for i in range(len(photoLst)):
        photoItm = photoLst[i]
        fileid = photoItm["fileid"]
        dlReq = wedriveFileDownloadApi(fileid)
        if dlReq["code"] == 0:
            file_path = dlReq["data"]["file_path"]
            upReq = uploadMediaApi(file_path)
            if upReq["code"] == 0:
                media_id = upReq["data"]["media_id"]
                photos.append(media_id)
    return photos


# repeated_id = "fmmRF6SIyTpV7j6rt5BixQyM2YwCADAN3lh3YcmaileiQNywrmU9hweSmihCkI3b7QDqOzqX3LNr1Rw3AHcatMZw"
def getFormAnswerApi(repeated_id, answer_ids):
    code = 0
    msg = "success"
    data = {}
    apiName = "读取收集表答案"
    logger.info(f"接口>>>{apiName}>>>开始调用")
    ACCESS_TOKEN = getAccessToken()
    if not ACCESS_TOKEN:
        code = 1
        msg = "获取access_token失败"
        apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>{apiOutput}")
        return {"code": code, "msg": msg, "data": data}
    url = HOST + "wedoc/get_form_answer?access_token=" + ACCESS_TOKEN
    d = {"repeated_id": repeated_id, "answer_ids": answer_ids}
    apiInput = f"1.repeated_id<{repeated_id}>;2.answer_ids<{answer_ids}>;"
    logger.info(f"接口>>>{apiName}>>>入参>>>\n{apiInput}")
    try:
        response = requests.post(url, json=d)
    except Exception as e:
        print("未知异常")
        print(e)
        code = 1
        msg = "未知异常"
        apiOutput = f"1.code<{code}>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    responseJson = response.json()
    logger.info(f"接口>>>{apiName}>>>返回结果>>>\n{responseJson}")
    if responseJson["errcode"] != 0:
        code = responseJson["errcode"]
        msg = responseJson["errmsg"]
        apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    else:
        answer = responseJson["answer"]["answer_list"][0]
        apiOutput = f"1.code<{code}>;2.msg<{msg}>;3.answer<{answer}>;"
        logger.info(f"接口>>>{apiName}>>>执行成功>>>\n{apiOutput}")
        # 创建时间
        ctime = answer["ctime"]
        # 'userid': 'DuHu',
        userid = answer["userid"]
        # reply
        reply = answer["reply"]
        content = reply["items"][0]['text_reply']
        location = reply["items"][1]['text_reply']
        photoLst = reply["items"][2]['file_extend_reply']
        data["ctime"] = ctime
        data["userid"] = userid
        data["content"] = content
        data["location"] = location
        data["photos"] = processFormPhotos(photoLst)
    return {"code": code, "msg": msg, "data": data}


def delFormApi(formid):
    code = 0
    msg = "success"
    data = {}
    apiName = "删除文档/收集表"
    logger.info(f"接口>>>{apiName}>>>开始调用")
    ACCESS_TOKEN = getAccessToken()
    if not ACCESS_TOKEN:
        code = 1
        msg = "获取access_token失败"
        apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
        return {"code": code, "msg": msg, "data": data}
    url = HOST + "wedoc/del_doc?access_token=" + ACCESS_TOKEN
    d = {"formid": formid}
    apiInput = f"1.formid<{formid}>;"
    logger.info(f"接口>>>{apiName}>>>入参>>>\n{apiInput}")
    try:
        response = requests.post(url, json=d)
        responseJson = response.json()
        logger.info(f"接口>>>{apiName}>>>返回结果>>>\n{responseJson}")
        if responseJson["errcode"] != 0:
            code = responseJson["errcode"]
            msg = responseJson["errmsg"]
            apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
            logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
        else:
            apiOutput = f"1.code<{code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiName}>>>执行成功>>>\n{apiOutput}")
    except Exception as e:
        print("未知异常")
        print(e)
        code = 1
        msg = "未知异常"
        apiOutput = f"1.code<{code}>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    return {"code": code, "msg": msg, "data": data}


def applyDailySpApi(replyId):
    code = 0
    msg = "success"
    data = {}
    apiName = "提交审批申请"
    logger.info(f"接口>>>{apiName}>>>开始调用")
    ACCESS_TOKEN = getAccessToken()
    if not ACCESS_TOKEN:
        code = 1
        msg = "获取access_token失败"
        apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
        return {"code": code, "msg": msg, "data": data}
    url = HOST + "oa/applyevent?access_token=" + ACCESS_TOKEN
    replyDaily = ClientVisitReplyDaily.objects.get(id=replyId)
    creator_userid = replyDaily.replier.wxid
    clientName = replyDaily.client_visit.client.name
    replierName = replyDaily.replier.name
    files = []
    photos = replyDaily.photos
    photos = ast.literal_eval(photos)
    for p in photos:
        files.append({"file_id": p})
    apiInput = f"1.replyId<{replyId}>;"
    logger.info(f"接口>>>{apiName}>>>入参>>>\n{apiInput}")
    d = {
        "creator_userid": creator_userid,
        "template_id": dailyTemplateId,
        "use_template_approver": 0,
        "approver": [
            {
                "attr": 1,
                "userid": ["DuHu"]
            }
        ],
        "notifyer": ["DuHu"],
        "notify_type": 1,
        "apply_data": {
            "contents": [
                {
                    "control": "Tips",
                    "id": "Tips-1704182187873",
                    "title": [
                        {
                            "text": "说明",
                            "lang": "zh_CN"
                        }
                    ],
                    "value": {},
                    "display": 1,
                    "require": 0
                },
                {
                    "control": "Text",
                    "id": "Text-1704182552250",
                    "title": [
                        {
                            "text": "客户名称",
                            "lang": "zh_CN"
                        }
                    ],
                    "value": {
                        "text": clientName
                    },
                    "display": 1,
                    "require": 0
                },
                {
                    "control": "Textarea",
                    "id": "Textarea-1704182604035",
                    "title": [
                        {
                            "text": "拜访情况",
                            "lang": "zh_CN"
                        }
                    ],
                    "value": {
                        "text": replyDaily.content
                    },
                    "display": 1,
                    "require": 0
                },
                {
                    "control": "Location",
                    "id": "Location-1704182581921",
                    "title": [
                        {
                            "text": "打卡300米",
                            "lang": "zh_CN"
                        }
                    ],
                    "value": {
                        "location": {
                            "latitude": "36.605908",
                            "longitude": "101.790571",
                            "title": "城东区夏都壹号君悦雅居(建新路东)",
                            "address": "西宁市城东区夏都壹号君悦雅居(建新路东)",
                            "time": 1704537734
                        }
                    },
                    "display": 1,
                    "require": 0
                },
                {
                    "control": "File",
                    "id": "File-1704182585427",
                    "title": [
                        {
                            "text": "照片",
                            "lang": "zh_CN"
                        }
                    ],
                    "value": {
                        "files": files
                    },
                    "display": 1,
                    "require": 0
                }
            ]
        },
        "summary_list": [
            {
                "summary_info": [{
                    "text": "客户：" + clientName,
                    "lang": "zh_CN"
                }]
            },
            {
                "summary_info": [{
                    "text": "提交人：" + replierName,
                    "lang": "zh_CN"
                }]
            },
            {
                "summary_info": [{
                    "text": "时间：" + replyDaily.created.strftime("%Y-%m-%d %H:%M:%S"),
                    "lang": "zh_CN"
                }]
            }
        ]
    }
    try:
        response = requests.post(url, json=d)
        responseJson = response.json()
        logger.info(f"接口>>>{apiName}>>>返回结果>>>\n{responseJson}")
        if responseJson["errcode"] != 0:
            code = responseJson["errcode"]
            msg = responseJson["errmsg"]
            apiOutput = f"1.code<{code}>; 2.msg<{msg}>;"
            logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
        else:
            sp_no = responseJson["sp_no"]
            data["sp_no"] = sp_no
            apiOutput = f"1.code<{code}>;2.msg<{msg}>;3.sp_no<{sp_no}>;"
            logger.info(f"接口>>>{apiName}>>>执行成功>>>\n{apiOutput}")
    except Exception as e:
        print("未知异常")
        print(e)
        code = 1
        msg = "未知异常"
        apiOutput = f"1.code<{code}>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiName}>>>执行失败>>>\n{apiOutput}")
    return {"code": code, "msg": msg, "data": data}


def processFormComplete(userId, createTime, formId):
    apiName = "开始处理收集表回复情况"
    logger.info(f"方法>>>{apiName}>>>开始调用")
    print("form_complete")
    clientvisit = ClientVisit.objects.get(formid=formId)
    clientvisit.status = 1
    clientvisit.save()
    # 1.获取收集表信息
    print("getFormInfoApi^^^1.获取收集表信息")
    infoReq = getFormInfoApi(formId)
    infoCode = infoReq["code"]
    if infoCode == 0:
        infoData = infoReq["data"]
        print("infoData", infoData)
        repeated_id = infoData["repeated_id"]
        # 2.获取收集表答案
        if clientvisit.kind == 1:
            answer_ids = [1, 2, 3]
        answerReq = getFormAnswerApi(repeated_id, answer_ids)
        answerCode = answerReq["code"]
        if answerCode == 0:
            answerData = answerReq["data"]
            print("answerData", answerData)
            # 4.处理MODEL
            if clientvisit.kind == 1:
                replyDaily = ClientVisitReplyDaily()
                replyDaily.client_visit = clientvisit
                replier = User.objects.get(wxid=answerData["userid"])
                replyDaily.replier = replier
                replyDaily.content = answerData["content"]
                replyDaily.location = answerData["location"]
                replyDaily.photos = answerData["photos"]
                replyDaily.save()
            # 3.删除收集表
            delReq = delFormApi(formId)
            # 5.发起审批
            if clientvisit.kind == 1:
                replyId = replyDaily.id
                applyReq = applyDailySpApi(replyId)
                if applyReq["code"] == 0:
                    applyData = applyReq["data"]
                    print("applyData", applyData)
                    sp_no = applyData["sp_no"]
                    replyDaily.sp_no = sp_no
                    replyDaily.save()
                    clientvisit.status = 2
                    clientvisit.save()


# 通用处理消息
def processMessage(msg_signature, timestamp, nonce, xmlStr):
    print("============回调===通用处理消息===============")
    wxcpt = WXBizMsgCrypt(TOKEN, AESKEY, CORPID)
    decCode, decData = wxcpt.DecryptMsg(xmlStr, msg_signature, timestamp, nonce)
    if decCode == 0:
        dicData = xmltodict.parse(decData)
        data = dicData["xml"]
        print("============回调===data===============/n", data)
        corpId = data["ToUserName"]
        if corpId != CORPID:
            print("============回调===错误corpId===============")
            return 1
        msgType = data["MsgType"]
        # 事件
        if msgType == "event":
            print("============回调===事件===============")
            event = data["Event"]
            # 文档相关
            if event == "doc_change":
                print("============回调===文档===============")
                changeType = data["ChangeType"]
                if changeType == "form_complete":
                    print("============回调===收集单回单===============")
                    userId = data["FromUserName"]
                    createTime = data["CreateTime"]
                    formId = data["FormId"]
                    processFormComplete(userId, createTime, formId)
            elif event == "sys_approval_change":
                print("============回调===审批===============")
                approvalInfo = data["ApprovalInfo"]
                statuChangeEvent = approvalInfo["StatuChangeEvent"]
                if statuChangeEvent != 2 or statuChangeEvent != 3:
                    return 1
                templateId = approvalInfo["TemplateId"]
                if templateId != dailyTemplateId or templateId != iceTemplateId:
                    return 1
                spRecord = approvalInfo["SpRecord"]
                spStatus = spRecord["SpStatus"]
                if spStatus != 2 or spStatus != 3:
                    return 1
                spNo = approvalInfo["SpNo"]
                try:
                    replyDaily = ClientVisitReplyDaily.objects.get(sp_no=spNo)
                    clientVisit = replyDaily.client_visit
                    clientVisit.status = spStatus + 1
                    clientVisit.save()
                except ClientVisitReplyDaily.DoesNotExist:
                    return 1
                details = spRecord["Details"]
                approver = details["Approver"]["UserId"]
                dailyReview = ClientVisitReplyDailyReview()
                dailyReview.reply = replyDaily
                dailyReview.status = spStatus
                dailyReview.approver = approver
                dailyReview.save()
        elif msgType == "text":
            print("============回调===文本===============")
            content = data["Content"]
        else:
            return 1
    else:
        return 1


# 返回码	说明
# -40001	签名验证错误
# -40002	xml/json解析失败
# -40003	sha加密生成签名失败
# -40004	AESKey 非法
# -40005	ReceiveId 校验错误
# -40006	AES 加密失败
# -40007	AES 解密失败
# -40008	解密后得到的buffer非法
# -40009	base64加密失败
# -40010	base64解密失败
# -40011	生成xml/json失败
@csrf_exempt
def CallBackView(request):
    if request.method == "GET":
        # 打印请求的查询参数
        print("GET parameters:", request.GET)
        msg_signature = request.GET.get('msg_signature')
        timestamp = request.GET.get('timestamp')
        nonce = request.GET.get('nonce')
        echostr = request.GET.get('echostr')
        # sVerifyEchoStr = urllib.parse.unquote(echostr)
        wxcpt = WXBizMsgCrypt(TOKEN, AESKEY, CORPID)
        ret, sEchoStr = wxcpt.VerifyURL(msg_signature, timestamp, nonce, echostr)
        if ret != 0:
            print("ERR: VerifyURL ret: " + str(ret))
            return HttpResponse(str(ret))
        else:
            return HttpResponse(sEchoStr)
    elif request.method == "POST":
        print("============回调调用===============")
        msg_signature = request.GET.get('msg_signature')
        timestamp = request.GET.get('timestamp')
        nonce = request.GET.get('nonce')
        xmlData = request.read()
        xmlStr = xmlData.decode('utf-8')
        processMessage(msg_signature, timestamp, nonce, xmlStr)
        return HttpResponse("OK", content_type="text/plain", status=200)
